package com.example.yoga.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.yoga.entity.*;
import com.example.yoga.service.IMsgService;
import com.example.yoga.service.IMvService;
import com.example.yoga.service.IUserService;
import com.example.yoga.util.JsonResult;
import com.example.yoga.util.PageDataResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liwenkai
 * @since 2021-02-20
 */
@RestController
@RequestMapping("/msg")
public class MsgController {

    @Autowired
    private IMsgService msgService;

    @Autowired
    private IUserService userService;

    /**
     * 新增留言
     * @param msg
     * @return
     */
    @RequestMapping(value="/addmsg",method = RequestMethod.POST)
    public JsonResult<Void> addMsg(@RequestBody Msg msg){
        //根据接收人id找到接收人
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("userId",msg.getFriend());
        User user = userService.getOne(wrapper);
        //将查到的用户名放入到这条记录中
        msg.setReceiver(user.getUsername());
        //记录当前时间
        msg.setSendTime(new Date());
        System.out.println(msg.toString());
        //进行新增操作(第一次)
        boolean b = msgService.save(msg);
        //进行新增操作(第二次),交换user和friend
        Integer flag1=msg.getUser();
        Integer flag2=msg.getFriend();
        msg.setUser(flag2);
        msg.setFriend(flag1);
        System.out.println(msg.toString());
        boolean c = msgService.save(msg);
        if (b&&c){
            return new JsonResult<>(2000,"添加成功！");
        }
        return new JsonResult<>(4000,"添加失败！");
    }

    /**
     * 根据用户名查询留言
     */
    @RequestMapping("/querymsg")
    public PageDataResult queryMsg(String name,Integer pageIndex,Integer pageSize,Integer currUserid){
        PageHelper.startPage(pageIndex,pageSize);
        if (name==null||name.length()==0){
           //查询全部留言,并按时间的最近排序
            QueryWrapper<Msg> msgQueryWrapper = new QueryWrapper<>();
            msgQueryWrapper.eq("user",currUserid);
            msgQueryWrapper.orderByDesc("send_time");
            List<Msg> msgList = msgService.list(msgQueryWrapper);
            //进行分页
            PageInfo<Msg> pageInfo = new PageInfo<Msg>(msgList);
            PageDataResult pdr = new PageDataResult();
            pdr.setList(pageInfo.getList());
            pdr.setTotals(Long.valueOf(pageInfo.getTotal()).intValue());
            return pdr;
        }
        QueryWrapper<Msg> wrapper = new QueryWrapper<>();
        wrapper.like("receiver",name);
        wrapper.eq("user",currUserid);
        wrapper.orderByDesc("send_time");
        List<Msg> list = msgService.list(wrapper);
        //进行分页
        PageInfo<Msg> pageInfo = new PageInfo<Msg>(list);
        PageDataResult pdr = new PageDataResult();
        pdr.setList(pageInfo.getList());
        pdr.setTotals(Long.valueOf(pageInfo.getTotal()).intValue());
        return pdr;
    }

    /**
     * 删除留言
     */
    @RequestMapping(value = "/delMsg",method = RequestMethod.DELETE)
    public JsonResult<Void> delMsg(Integer id){
        //删除留言
        boolean b = msgService.removeById(id);
        if(b){
            return new JsonResult<>(2000,"删除成功！");
        }
        return new JsonResult<>(4000,"删除异常！");
    }

    /**
     * 批量删除
     */
    @RequestMapping(value = "/delMore",method = RequestMethod.POST)
    public JsonResult<Void> delMvMore(@RequestBody List<Integer> ids){
        if (!ObjectUtils.isEmpty(ids)){
            boolean b = msgService.removeByIds(ids);
            if (b){
                return new JsonResult<>(2000,"删除成功");
            }
        }
        return new JsonResult<>(4000,"请选择要删除的留言！");
    }

    /**
     * 获取未读留言：status为0，未读
     */
    @RequestMapping(value = "/getUnreadList",method = RequestMethod.GET)
    public JsonResult<List> getUnreadList(Integer id) {
        System.out.println(id);
        //根据当前id查询用户名
        User user = userService.getById(id);
        //未读留言必须id为当前用户,留言的接收者也为当前用户,并且状态标记为0
        QueryWrapper<Msg> wrapper = new QueryWrapper<>();
        wrapper.eq("user",id);
        wrapper.eq("receiver",user.getUsername());
        wrapper.eq("status",0);
        List<Msg> msgList = msgService.list(wrapper);
        if (msgList.size()>0){
            return new JsonResult<>(2000,msgList) ;
        }
        return new JsonResult<>(4000,"暂无消息！") ;
    }

    /**
     * 获取已读留言，status为1，已读
     */
    @RequestMapping(value = "/getReadList",method = RequestMethod.GET)
    public JsonResult<List> getReadList(Integer id) {
        System.out.println(id);
        //根据当前id查询用户名
        User user = userService.getById(id);
        //未读留言必须id为当前用户,留言的接收者也为当前用户,并且状态标记为0
        QueryWrapper<Msg> wrapper = new QueryWrapper<>();
        wrapper.eq("user",id);
        wrapper.eq("receiver",user.getUsername());
        wrapper.eq("status",1);
        List<Msg> msgList = msgService.list(wrapper);
        if (msgList.size()>0){
            return new JsonResult<>(2000,msgList) ;
        }
        return new JsonResult<>(4000,"暂无消息！") ;
    }
    /**
     * 获取放入回收站的留言，status为2，回收站
     */
    @RequestMapping(value = "/getRecycleList",method = RequestMethod.GET)
    public JsonResult<List> getRecycleList(Integer id) {
        System.out.println(id);
        //根据当前id查询用户名
        User user = userService.getById(id);
        //未读留言必须id为当前用户,留言的接收者也为当前用户,并且状态标记为0
        QueryWrapper<Msg> wrapper = new QueryWrapper<>();
        wrapper.eq("user",id);
        wrapper.eq("receiver",user.getUsername());
        wrapper.eq("status",2);
        List<Msg> msgList = msgService.list(wrapper);
        if (msgList.size()>0){
            return new JsonResult<>(2000,msgList) ;
        }
        return new JsonResult<>(4000,"暂无消息！") ;
    }

    /**
     * markRead
     * flag=0,标记已读操作
     * flag=1,标记放入回收站
     * flag=2,标记还原操作
     */
    @RequestMapping(value = "/markRead",method = RequestMethod.PUT)
    public JsonResult<Void> markRead(Integer flag,Integer id) {
        //判断flag的值，0为已读操作，1为放入回收站，2为还原操作
        System.out.println(flag+"flag");
        System.out.println(id+"id");
        UpdateWrapper<Msg> updateWrapper = new UpdateWrapper<>();
        UpdateWrapper<Msg> updateWrapper2 = new UpdateWrapper<>();
        if (flag == 1) {
            //把未读状态0改为已读状态，并插入读取时间,需要更改两条记录
            updateWrapper.eq("MsgId", id);
            //构造一个对象
            Msg msg = new Msg();
            msg.setReadTime(new Date());
            msg.setStatus(flag);
            boolean b = msgService.update(msg, updateWrapper);
            //第二条记录
            updateWrapper2.eq("MsgId", id-1);
            boolean b1 = msgService.update(msg, updateWrapper2);
            if (b&&b1) {
                return new JsonResult<>(2000, "标记已读成功！");
            } else {
                return new JsonResult<>(4000, "标记失败！");
            }
        }
        if (flag == 2) {
            //把已读状态改为回收站状态
            updateWrapper.eq("MsgId", id);
            //构造一个对象
            Msg msg = new Msg();
            msg.setStatus(flag);
            boolean b = msgService.update(msg, updateWrapper);
            if (b) {
                return new JsonResult<>(2000, "放入回收站成功！");
            } else {
                return new JsonResult<>(4000, "放入回收站失败！");
            }
        }
        if (flag == 3) {
            //把回收站状态2改为已读状态1
            updateWrapper.eq("MsgId", id);
            //构造一个对象
            Msg msg = new Msg();
            msg.setStatus(1);
            boolean b = msgService.update(msg, updateWrapper);
            if (b) {
                return new JsonResult<>(2000, "还原成功！");
            } else {
                return new JsonResult<>(4000, "还原失败！");
            }
        }
        return new JsonResult<>(4000, "标记异常！");
    }

    /**
     * 批量放入回收站
     *
     */
    @RequestMapping(value = "/cycleByIds",method = RequestMethod.POST)
    public JsonResult<Void> cycleByIds(@RequestBody List<Integer> ids){
        if (!ObjectUtils.isEmpty(ids)){
            UpdateWrapper<Msg> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("status",2).in("msgId",ids);
            boolean b = msgService.update(updateWrapper);
            if (b){
                return new JsonResult<>(2000,"删除成功！");
            }
        }
        return new JsonResult<>(4000,"删除失败！");
    }

    /**
     * 批量删除deleByIds
     */
    @RequestMapping(value = "/deleByIds",method = RequestMethod.POST)
    public JsonResult<Void> deleByIds(@RequestBody List<Integer> ids){
        if (!ObjectUtils.isEmpty(ids)){
            boolean b = msgService.removeByIds(ids);
            if (b){
                return new JsonResult<>(2000,"删除成功");
            }
        }
        return new JsonResult<>(4000,"请选择要删除的留言！");
    }

    /**
     * 批量标为已读
     *
     */
    @RequestMapping(value = "/readByIds",method = RequestMethod.POST)
    public JsonResult<Void> readByIds(@RequestBody List<Integer> ids){
        if (!ObjectUtils.isEmpty(ids)){
            //记录已读的另外一条记录的id
            ArrayList arrayList = new ArrayList<Integer>();
            for (int i = 0; i <ids.size(); i++) {
                arrayList.add(ids.get(i)-1);
            }
            System.out.println(ids);
            System.out.println(arrayList);
            UpdateWrapper<Msg> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("read_time",new Date()).set("status",1).in("msgId",ids);
            boolean b = msgService.update(updateWrapper);
            //标记记录已读的另外一条记录
            UpdateWrapper<Msg> updateWrapper2 = new UpdateWrapper<>();
            updateWrapper2.set("read_time",new Date()).set("status",1).in("msgId",arrayList);
            boolean b2 = msgService.update(updateWrapper2);
            if (b&&b2){
                return new JsonResult<>(2000,"全部已读！");
            }
        }
        return new JsonResult<>(4000,"标记失败！");
    }
}

